package com.ysu.concurrency.thread.threadpool;

import java.util.concurrent.*;

/**
 * Executors 工具类： 3大方法
 * */
public class TestExecutors {
    public static void main(String[] args) {
       /**
        *
        * 禁止使用Executors创建
        * ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程
        * ExecutorService threadPool = Executors.newFixedThreadPool(5);//创建一个固定大小的线程池
        * ExecutorService threadPool = Executors.newCachedThreadPool();//创建一个可伸缩的线程池
        *
        * */

       /**
        * ThreadPoolExecutor 手动创建线程池
        * Runtime.getRuntime().availableProcessors() 获取服务器cpu核数
        * */
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3, Runtime.getRuntime().availableProcessors(), 3, TimeUnit.SECONDS, new LinkedBlockingQueue<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        try{
            for (int i = 0; i < 20; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName() + "done");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭线程池
            threadPool.shutdown();
        }
    }
}
